/*
 * Copyright (c) 2007 Compl Yue Still, All Rights Reserved.
 */

package hbi.domain.java;

import hbi.domain.DomainController;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public abstract class JavaDomain implements DomainController
{

    public static final int MAX_STRING_LENGTH = 20 * 1024 * 1024;

    public static final int MAX_BINARY_LENGTH = 20 * 1024 * 1024;

    public static final int MAX_TYPE_NAME_LENGTH = 1200;

    public int getControllerVersion()
    {
        // 1.0
        return 0x0100;
    }

    public boolean isControllerVersionSupported(int version)
    {
        // enforce exact match here
        return version == this.getControllerVersion();
    }

    public String getDomainName()
    {
        return this.getClass().getSimpleName();
    }

    public Class<? extends JavaDomain> getFormalDomainType()
    {
        return this.getClass();
    }

    private final ExecutorService hostingService;

    protected JavaDomain(int nHostingThreads)
    {
        if (nHostingThreads < 2)
            throw new IllegalArgumentException("Too few hosting threads: "
                + nHostingThreads);

        this.hostingService = new ThreadPoolExecutor(nHostingThreads,
            nHostingThreads * 2, 10L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());
    }

    protected <R extends DomainController> void localGatewaySetup(
        JavaGateway<? extends JavaDomain, R> gateway,
        Class<? extends R> remoteDomainType)
    {
    }

    public void hostExecution(int requestedControllerVersion, Runnable task)
    {
        hostingService.submit(task);
    }

    /**
     * Judge the exception type and retryCount to determine whether the task can
     * be retried, and schedule a retry if so.
     * <p>
     * Default implementation here throws an
     * {@link UnsupportedOperationException} wrapping the exception.
     * 
     * @param exception
     * @param retryCount
     * @param requestedControllerVersion
     * @param task
     */
    public void retryExecution(Throwable exception, int retryCount,
        int requestedControllerVersion, Runnable task)
    {
        throw new UnsupportedOperationException(exception);
    }

    public void shutdown()
    {
        hostingService.shutdown();
    }

}
